package com.example.shopping.controller;

import com.example.shopping.dto.CartItem;
import com.example.shopping.entity.Category;
import com.example.shopping.entity.Goods;
import com.example.shopping.entity.User;
import com.example.shopping.service.CartService;
import com.example.shopping.service.CategoryService;
import com.example.shopping.service.GoodsService;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
public class IndexController {

    @Autowired
    private GoodsService goodsService;
    @Autowired
    private CategoryService categoryService;

    @Autowired
    private CartService cartService;

    private static int pageSize = 5;

    //进入到首页
    @RequestMapping("/")
    public String index(@RequestParam(defaultValue = "1") int page, @RequestParam(defaultValue = "") String searchName, @RequestParam(defaultValue = "0") Integer categoryId, Model model, HttpSession session) {
        //判断是否已登录
        User user = (User) session.getAttribute("loginUser");
        if (user == null) {
            return "redirect:/user/login";
        }
        //cart
        List<CartItem> cartItems = cartService.getCar(user.getId());
        model.addAttribute("cartItems", cartItems);
        model.addAttribute("cartCount", cartItems.size());


        //categories
        List<Category> categories = categoryService.getAll();
        model.addAttribute("categories", categories);

        //hotGoodList
        List<Goods> hotGoodList = goodsService.selectAllHot();
        model.addAttribute("hotGoodList", hotGoodList);


        //获取页数以及验证页数的有效性
        // 获取总记录数
        long total = goodsService.count(searchName);
        // 计算总页数
        int totalPages = (int) Math.ceil((double) total / pageSize);
        // 确保页码在有效范围内
        if (page < 1) {
            page = 1;
        }
        if (page > totalPages) {
            page = totalPages;
        }


        //拿到所有的商品返回给页面
        List<Goods> goodsList = goodsService.findByPage(page, pageSize, searchName, categoryId);

        // 计算总页数
        totalPages = (int) Math.ceil((double) goodsList.size() / pageSize);
        //将数据发送给jsp页面，同时可以用jstl标签以goodsList名称来使用数据
        model.addAttribute("goodList", goodsList);
        model.addAttribute("currentPage", page);
        model.addAttribute("totalPages", (int) Math.ceil((double) total / pageSize));
        model.addAttribute("total", total);
        return "index";//找到/WEB-INF/pages/index.jsp
    }


}

